/* eslint-disable react/jsx-key */
import { Upload, Button, message, notification } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { formFetch } from '@/utils/doFetch';

import React from 'react';

class Uploadcom extends React.Component {
  state = {
    fileList: [],
    uploading: false,
  };

  handleUpload = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file);
    });

    this.setState({
      uploading: true,
    });

    formFetch({ url: '/wbn-api/voucher/batch_import_vouchers', params: formData }).then((res) => {
      if (res.code == 0) {
        this.setState({
          fileList: [],
          uploading: false,
        });
        message.success('上传成功');
        this.props.reload();
      } else {
        this.setState({
          uploading: false,
        });
      }
    });
  };

  render() {
    const { uploading, fileList } = this.state;
    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          return {
            fileList: [],
          };
        });
      },
      beforeUpload: (file) => {
        this.setState((state) => ({
          fileList: [file],
        }));
        return false;
      },
      fileList,
      maxCount: 1,
    };

    return (
      <>
        <Upload.Dragger {...props}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或者拖拽文件上传</p>
          <p className="ant-upload-hint">批量导入仅支持单文件导入</p>
        </Upload.Dragger>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{ marginTop: 16, width: '100%' }}
        >
          {uploading ? '上传中' : '开始上传'}
        </Button>
      </>
    );
  }
}

export default Uploadcom;
